package com.laomuji.android.mvvm.utils.google

import android.content.Context
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.android.installreferrer.api.ReferrerDetails
import com.laomuji.android.mvvm.http.common.GsonManager
import com.laomuji.android.mvvm.utils.MyLog

/**
 * GooglePlay 归因
 * 获取从GooglePlay安装的信息
 * @author laomuji666
 * @since 2024/4/29
 */
object GoogleInstallReferrer {

    /**
     * 获取的归因参数
     * @param installReferrer 已安装包的引用 URL
     * @param referrerClickTimestampSeconds 发生引荐来源网址点击时的时间戳
     * @param installBeginTimestampSeconds 安装开始时的时间戳
     * @param googlePlayInstantParam 是否在过去7天内启动过app
     */
    data class InstallReferrerInfo(
        val installReferrer: String,
        val referrerClickTimestampSeconds: Long,
        val installBeginTimestampSeconds: Long,
        val googlePlayInstantParam: Boolean
    )

    private lateinit var referrerClient: InstallReferrerClient
    private const val TAG = "tag_referrer"

    fun initGoogleInstallReferrer(context: Context, onGetReferrer:(InstallReferrerInfo)->Unit){
        referrerClient = InstallReferrerClient.newBuilder(context).build()
        referrerClient.startConnection(object : InstallReferrerStateListener {

            override fun onInstallReferrerSetupFinished(responseCode: Int) {
                when (responseCode) {
                    InstallReferrerClient.InstallReferrerResponse.OK -> {
                        //连接成功,可以获取归因数据
                        val response: ReferrerDetails = referrerClient.installReferrer
                        val installReferrerInfo = InstallReferrerInfo(
                            response.installReferrer,
                            response.referrerClickTimestampSeconds,
                            response.installBeginTimestampSeconds,
                            response.googlePlayInstantParam
                        )
                        MyLog.iCustom(TAG, GsonManager.gson.toJson(installReferrerInfo))
                        onGetReferrer(installReferrerInfo)
                    }
                    InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED -> {
                        //GooglePlay版本不支持
                        MyLog.iCustom(TAG, "FEATURE_NOT_SUPPORTED")
                    }
                    InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE -> {
                        //连接不可用
                        MyLog.iCustom(TAG, "SERVICE_UNAVAILABLE")
                    }
                }
            }

            override fun onInstallReferrerServiceDisconnected() {
                //连接GooglePlay失败
                MyLog.iCustom(TAG, "onInstallReferrerServiceDisconnected")
            }
        })
    }


}